package com.company.cloud.oss.utils;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.HttpContextUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.oss.config.OssConfig;

import cn.hutool.core.util.StrUtil;
import com.company.cloud.oss.constant.OssErrorEnum;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class AliYunOssUtils {


	/**
	 * OSS签名
	 * @param ossConfig：
	 * @param companyNo：
	 * @param userId：
	 * @param widths :图片压缩尺寸
	 * @param quality :图片质量处理
	 * */
	public static Map<String, String> getOssSign(OssConfig ossConfig,
													   String companyNo,
													   Integer userId,
													   Set<Integer> widths,
												 	   int quality,
												       String isImg

	){
		OSS client = new OSSClientBuilder().build(ossConfig.getEndpoint(),
				ossConfig.getAccessId(), ossConfig.getAccessKey());
		try {
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossConfig.getDir());

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			Map<String, String> respMap = new LinkedHashMap<String, String>();
			respMap.put("accessid", ossConfig.getAccessId());
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			respMap.put("dir", ossConfig.getDir());
			respMap.put("host", ossConfig.getHost());
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			String base64CallbackBody= AliYunOssUtils.getJasonCallback(ossConfig,companyNo,userId,widths,quality,isImg);
			respMap.put("callback", base64CallbackBody);
			return respMap;
		} catch (Exception e) {
			System.out.println("+++++++++++++++AliYunOSS callback模式生成签名错误++++++++++++ ");
			e.printStackTrace();
			throw new BusinessException(OssErrorEnum.OSS_Sign_Error);
		}

	}

	public static AliYunOssCallbackModel getCallbackModel(String callbackBody) {
		JSONObject jsonObj= JSON.parseObject(callbackBody);
		AliYunOssCallbackModel data=new AliYunOssCallbackModel();
		data.setFileName(jsonObj.getString("fileName"));
		data.setFormat(jsonObj.getString("format"));
		data.setMimeType(jsonObj.getString("mimeType"));
		data.setBucket(jsonObj.getString("bucket"));
		data.setEtag(jsonObj.getString("etag"));
		data.setSize(jsonObj.getLongValue("size"));
		data.setHeight(jsonObj.getIntValue("height"));
		data.setWidth(jsonObj.getIntValue("width"));
		data.setBucket(jsonObj.getString("bucket"));
		data.setCompanyNo(jsonObj.getString("x:company"));
		data.setUserId(jsonObj.getString("x:userId"));
		data.setResizeWidth(jsonObj.getString("x:resize"));
		data.setQuality(jsonObj.getIntValue("x:quality"));
		return data;
	}
	
	
	public static String getJasonCallback(OssConfig cloudStorageConfig,
										  String companyNo,Integer userId,
										  Set<Integer> widths, int quality,
										  String isImg) {
		String resize;
		if(ArrayUtil.isNotEmpty(widths)){
			resize= StrSplitUtils.list2string(widths);
		}else{
			resize="0";
		}
		if(quality<1 || quality>=100){
			quality=0;
		}
		JSONObject jasonCallback = new JSONObject();
		jasonCallback.put("callbackUrl", cloudStorageConfig.getCallbackUrl());
		jasonCallback.put("callbackBodyType", "application/json");

		if(StrUtil.isNotEmpty(isImg) || BaseConstant.YNEnum.YES.getCode().equals(isImg)){
			String callbackBody= StrUtil.format("{"
							+ "\"fileName\":{},"
							+ "\"mimeType\":{},"
							+"\"bucket\":{},"
							+"\"etag\":{},"
							+ "\"size\":{},"
							//+"\"height\":{},"
							//+"\"width\":{},"
							+"\"format\":{},"
							+"\"x:company\":\"{}\","
							+"\"x:userId\":\"{}\","
							+"\"x:resize\":\"{}\","
							+"\"x:quality\":\"{}\""
							+ "}"
					,"${object}"
					,"${mimeType}"
					,"${bucket}"
					,"${etag}"
					,"${size}"
					//,"${imageInfo.height}"
					//,"${imageInfo.width}"
					,"${imageInfo.format}"
					,companyNo
					,userId
					,resize
					,quality
			);
			jasonCallback.put("callbackBody",callbackBody);
		}else{
			String callbackBody= StrUtil.format("{"
							+ "\"fileName\":{},"
							+ "\"mimeType\":{},"
							+"\"bucket\":{},"
							+"\"etag\":{},"
							+ "\"size\":{},"
							+"\"x:company\":\"{}\","
							+"\"x:userId\":\"{}\","
							+"\"x:resize\":\"{}\","
							+"\"x:quality\":\"{}\""
							+ "}"
					,"${object}"
					,"${mimeType}"
					,"${bucket}"
					,"${etag}"
					,"${size}"
					,companyNo
					,userId
					,resize
					,quality
			);
			jasonCallback.put("callbackBody",callbackBody);
		}
		String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
		return base64CallbackBody;
	}




	

	public static void main(String[] args) {
//		String callbackBody= StrUtil.format("{"
//				+ "\"filename\":{},"
//				+ "\"mimeType\":{},"
//				+ "\"size\":{},"
//				+"\"height\":{},"
//				+"\"width\":{},"
//				+"\"format\":{},"
//				+"\"x:company\":\"{}\","
//				+"\"x:userId\":\"{}\""
//				+ "}"
//				, "${object}"
//				,"${mimeType}"
//				,"${size}"
//				,"${imageInfo.height}"
//				,"${imageInfo.width}"
//				,"${imageInfo.format}"
//				,"wjjj"
//				,"111"
//		);
//		System.out.println(callbackBody);

//		String url="http://image-demo.oss-cn-hangzhou.aliyuncs.com/f.jpg";
//		String parameters="x-oss-process=image/info";
//		String data;
//		if(url.indexOf("?")>0){
//			data=StrUtil.format("{}&{}",url,parameters);
//		}else{
//			data=StrUtil.format("{}?{}",url,parameters);
//		}
//		System.out.println(data);
	}
	
	
	
	

	
}
